package me.macd.mindoc.config.shiro;

import me.macd.mindoc.model.Members;
import me.macd.mindoc.service.MemberService;
import me.macd.mindoc.util.constants.Constants;
import me.macd.mindoc.util.constants.Status;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: mindoc
 * @description: 登录用户验证
 * @author: 2018-09-19
 * @create: 2018-09-19 09:29
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private MemberService memberService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String loginName = (String) token.getPrincipal();
        Members member = memberService.findByAccount(loginName);
        if (member == null) {
            //没找到帐号
            throw new UnknownAccountException();
        }

        if (!Status.valid.getStatus().equals(member.getStatus())) {
            // 非有效用户
            throw new LockedAccountException();
        }

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                member.getAccount(),
                member.getPassword(),
                //ByteSource.Util.bytes(member.getUsername() + user.getSalt()), //salt=username+salt
                getName()
        );
        //session中不需要保存密码
        member.setPassword("");
        //将用户信息放入session中
        SecurityUtils.getSubject().getSession().setAttribute(Constants.SESSION_USER_INFO, member);
        return authenticationInfo;
    }
}
